package com.zr.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zr.shortlink.admin.common.convention.exception.ClientException;
import com.zr.shortlink.admin.dao.entity.UserDo;
import com.zr.shortlink.admin.dao.mapper.UserMapper;
import com.zr.shortlink.admin.dto.req.UserLoginReqDTO;
import com.zr.shortlink.admin.dto.req.UserRegisterReqDTO;
import com.zr.shortlink.admin.dto.req.UserUpdateReqDTO;
import com.zr.shortlink.admin.dto.resp.UserLoginRespDTO;
import com.zr.shortlink.admin.dto.resp.UserRespDTO;
import com.zr.shortlink.admin.service.UserService;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBloomFilter;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.UUID;

import static com.zr.shortlink.admin.common.enums.UserErrorCodeEnum.USER_NAME_EXIST;
import static com.zr.shortlink.admin.common.enums.UserErrorCodeEnum.USER_SAVE_ERROR;

@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDo> implements UserService {


    private final RBloomFilter<String> userRegisterCachePenetrationBloomFilter;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public UserLoginRespDTO login(UserLoginReqDTO requestparam) {
        LambdaQueryWrapper<UserDo> wrapper = Wrappers.lambdaQuery(UserDo.class)
                .eq(UserDo::getUsername, requestparam.getUsername())
                .eq(UserDo::getPassword, requestparam.getPassword())
                .eq(UserDo::getDelFlag, 0);
        UserDo userDo = baseMapper.selectOne(wrapper);
        if(userDo == null) {
            throw new ClientException("用户不存在");
        }
        if(stringRedisTemplate.hasKey("login_" + requestparam.getUsername())){
            throw new ClientException("请勿重复登录");
        }
        /**
         * Hash
         * key:login_用户名
         * value：
         *  key：token标识
         *  value：json字符串（用户信息）
         */
        String uuid = UUID.randomUUID().toString();
        HashMap<String, Object> userInfoMap = new HashMap<>();
        userInfoMap.put("token",JSON.toJSONString(userDo));
        stringRedisTemplate.opsForHash().put("login_" + requestparam.getUsername(), uuid, JSON.toJSONString(userInfoMap));
        stringRedisTemplate.expire("login_" + requestparam.getUsername(),30l, java.util.concurrent.TimeUnit.MINUTES);
        return new UserLoginRespDTO(uuid);
    }
    @Override
    public Boolean checkLogin(String username,String token) {


        return stringRedisTemplate.opsForHash().get("login_" + username, token)!=null;
    }

    @Override
    public UserRespDTO getUserByUsername(String username) {
        LambdaQueryWrapper<UserDo> queryWrapper = Wrappers.<UserDo>lambdaQuery()
                .eq(UserDo::getUsername, username);
        UserDo userDo = baseMapper.selectOne(queryWrapper);

        if (userDo == null) {
            return null; // 或者返回空对象或抛出自定义异常
        }

        UserRespDTO result = new UserRespDTO();
        BeanUtils.copyProperties(result, userDo);
        return result;
    }

    public boolean hasUsername(String username) {
        return !userRegisterCachePenetrationBloomFilter.contains(username);
    }

    @Override
    public void register(UserRegisterReqDTO requestparam) {
        if(!hasUsername(requestparam.getUsername())){
            throw new ClientException(USER_NAME_EXIST);
        }
        int insert = baseMapper.insert(BeanUtil.toBean(requestparam, UserDo.class));
        stringRedisTemplate.opsForHash().put("login" + requestparam.getUsername(), "token", JSON.toJSONString(requestparam));
        stringRedisTemplate.expire("login" + requestparam.getUsername(),30l, java.util.concurrent.TimeUnit.MINUTES);

        if(insert < 1){
            throw new ClientException(USER_SAVE_ERROR);
        }
        //TODO

    }

    @Override
    public void update(UserUpdateReqDTO requestparam) {
        //验证当前用户是否为登录用户
        LambdaUpdateWrapper<UserDo> wrapper = Wrappers.lambdaUpdate(UserDo.class)
                .eq(UserDo::getUsername, requestparam.getUsername());
        baseMapper.update(BeanUtil.toBean(requestparam, UserDo.class),wrapper);
    }



}
